import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs';

import { IElecBicycleUser } from 'app/shared/model/elec-bicycle-user.model';
import { ElecBicycleUserService } from './elec-bicycle-user.service';

@Component({
    selector: 'jhi-elec-bicycle-user-update',
    templateUrl: './elec-bicycle-user-update.component.html'
})
export class ElecBicycleUserUpdateComponent implements OnInit {
    private _elecBicycleUser: IElecBicycleUser;
    isSaving: boolean;

    constructor(private elecBicycleUserService: ElecBicycleUserService, private activatedRoute: ActivatedRoute) {}

    ngOnInit() {
        this.isSaving = false;
        this.activatedRoute.data.subscribe(({ elecBicycleUser }) => {
            this.elecBicycleUser = elecBicycleUser;
        });
    }

    previousState() {
        window.history.back();
    }

    save() {
        this.isSaving = true;
        if (this.elecBicycleUser.id !== undefined) {
            this.subscribeToSaveResponse(this.elecBicycleUserService.update(this.elecBicycleUser));
        } else {
            this.subscribeToSaveResponse(this.elecBicycleUserService.create(this.elecBicycleUser));
        }
    }

    private subscribeToSaveResponse(result: Observable<HttpResponse<IElecBicycleUser>>) {
        result.subscribe((res: HttpResponse<IElecBicycleUser>) => this.onSaveSuccess(), (res: HttpErrorResponse) => this.onSaveError());
    }

    private onSaveSuccess() {
        this.isSaving = false;
        this.previousState();
    }

    private onSaveError() {
        this.isSaving = false;
    }
    get elecBicycleUser() {
        return this._elecBicycleUser;
    }

    set elecBicycleUser(elecBicycleUser: IElecBicycleUser) {
        this._elecBicycleUser = elecBicycleUser;
    }
}
